function [I0, I1, V] = slsegs(values)
%SLSEGS Divides a vector of values into segments
%
% [ Syntax ]
%   - [I0, I1, V] = slsegs(values)
%
% [ Arguments ]
%   - values:       the sorted values to be segmented
%   - I0:           the first indices of segments
%   - I1:           the last indices of segments
%   - V:            the values of segments
%
% [ Description ]
%   - [I0, I1, V] = slsegs(values) divides a vector of values into 
%     segments, such that the values in each segment are the same.
%
% [ Examples ]
%   - Suppose V is [1 1 1 1 2 2 3 3 3 2 2], then the results are
%     \{
%           I0 = [1 5 7 10]
%           I1 = [4 6 9 11]
%           V  = [1 2 3 2]
%     \}
%
% [ History ]
%   - Created by Dahua Lin, on Dec 19, 2007
%

%% parse and verify input arguments

assert(islogical(values) || isnumeric(values), ...
    'sltoolbox:slsegs:invalidarg', ...
    'The values should be of numeric or logical type.');

assert(isvector(values), ...
    'sltoolbox:slsegs:invalidarg', ...
    'The values should be a vector.');


%% main

% for special case: values is a scalar

if isscalar(values)
    I0 = 1;
    I1 = 1;
    V = values;
    return;
end

% locate boundaries

chp = find(diff(values));

if size(values, 1) == 1  % row vector    
    I0 = [1, chp + 1];
    if nargout >= 2
        I1 = [chp, length(values)];     
    end
else                     % column vector
    I0 = [1; chp + 1];
    if nargout >= 2
        I1 = [chp; length(values)];
    end
end

% get values

if nargout >= 3
    V = values(I0);
end
